<template>
  <div class="spec-preview" @mousemove="mouseMoveHandle">
    <img v-show="imgUrl" :src="imgUrl" />
    <div class="event"></div>
    <div class="big">
      <img v-show="imgUrl" :src="imgUrl" ref="bigImg" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
export default {
  name: "Zoom",
  props: ["skuDefaultImg"],
  data(){
    return{
      imgUrl:""
    }
  },
  mounted(){
    // 绑定自定义事件，接收缩略图组件传递过来的需要展示的图片
    this.$bus.$on("changeImgUrl",(imgUrl)=>{
      this.imgUrl = imgUrl.imgUrl
    })
  },
  watch:{
    // imgUrl的初始值为空，如果不监听处理的话不点击缩略图切换大图一直都不会显示
    skuDefaultImg(newVal){
      this.imgUrl=newVal
    }
  },
  methods: {
    // 鼠标移动放大镜效果
    mouseMoveHandle(e) {
      // 获取当前鼠标到容器的距离
      let toBox = {
        x: e.offsetX,
        y: e.offsetY,
      };
      // 获取当前鼠标到蒙版的距离(mask和容器都没有边框用client和offset都可以)
      let toMask = {
        x: this.$refs.mask.clientWidth,
        y: this.$refs.mask.clientHeight,
      };
      // 蒙版移动的距离
      let mask = {
        x: toBox.x - toMask.x / 2,
        y: toBox.y - toMask.y / 2,
      };
      //蒙版位置的限制
      if (mask.x < 0) {
        mask.x = 0;
      }
      if (mask.y < 0) {
        mask.y = 0;
      }
      if (mask.x > e.target.clientWidth - toMask.x) {
        mask.x = e.target.clientHeight - toMask.x;
      }
      if (mask.y > e.target.clientWidth - toMask.y) {
        mask.y = e.target.clientHeight - toMask.y;
      }
      // 蒙版的位置
      this.$refs.mask.style.left = mask.x + "px";
      this.$refs.mask.style.top = mask.y + "px";

      //放大镜的位置
      this.$refs.bigImg.style.left = -2 * mask.x + "px";
      this.$refs.bigImg.style.top = -2 * mask.y + "px";
    },
  },
};
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>